package com.hzj.controller;

import com.hzj.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class StudentController {
    @Autowired
    @Qualifier("userServiceImpl")
    UserService us;

    @RequestMapping("/add")
    public String AddStudent(Model model) {
        model.addAttribute("userList", us.query());
        return "student/add";
    }

    @RequestMapping("/update")
    public String updateStudent() {
        return "student/update";
    }

    @PostMapping("/login")
    public String login(String username, String userpwd, Model model) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, userpwd);
        try {
            token.setRememberMe(true);
//            执行登录操作，shiro帮你验证，如果有错误就会报异常
            subject.login(token);

            return "../static/index";
        } catch (UnknownAccountException e) {
            model.addAttribute("error", "用户名不存在");
            return "student/login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("error", "密码不存在");
            return "student/login";
        }


    }

    @RequestMapping("/out")
    public String out() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/tologin";
    }

    @RequestMapping("/tologin")
    public String tologin() {
        return "student/login";
    }

    @RequestMapping("/toadmin")
    public String toadmin() {
        return "student/admin";
    }

    @RequestMapping("/unauthorized")
    @ResponseBody
    public String unauthorized() {
        return "未经授权无法访问此页面";
    }
}
